/*
   Copyright 2010 the original author or authors

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package com.googlecode.flightreports.flightlist;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;

import com.googlecode.kohmori.reportgen.AbstractSQLSource;
import com.googlecode.kohmori.springmvc.DefaultReportParams;

/* 
 * This class creates the report object and uses SQL to populate its values.
 */
@SuppressWarnings("restriction")
public class ReportSQL extends AbstractSQLSource {

   @Override
   public String getJAXBPackageList() {
      return "com.googlecode.flightreports.flightlist";
   }

   /**
    * Creates a report object
    * 
    * @param dbConn
    *           Connection object to run SQL
    * @return report instance, null if no report found
    */
   public JAXBElement<?> createReportObject(Connection dbConn,
         DefaultReportParams reportParams) throws SQLException {
      SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm");
      ReportParams rP = (ReportParams) reportParams;
      FlightListByAirlineReport rpt = new FlightListByAirlineReport();
      rpt.setAirlineName(rP.getAirlineName());
      rpt.setSortedBy(rP.getSortedBy());

      try {
         String sqlStatement = "SELECT " + "current_timestamp as run_date "
               + "from sysibm.sysdummy1";

         PreparedStatement pstmt = dbConn.prepareStatement(sqlStatement);
         ResultSet rs = pstmt.executeQuery();

         if (rs.next()) {
            rpt.setRunDate(rs.getTimestamp("run_date"));
         } else {
            throw new SQLException("System error: " + "Database access problem");
         }

         rs.close();

         sqlStatement = "SELECT flight_number, "
               + "origin, destination, depart_time,"
               + "arrive_time, miles, number_of_segments, " + "aircraft_type "
               + "from APP.V_FLIGHTLIST " + "where airline_name = ? "
               + "order by " + rP.getSortDBColumnName() + ", flight_number";

         pstmt = dbConn.prepareStatement(sqlStatement);
         pstmt.setString(1, rP.getAirlineName());
         rs = pstmt.executeQuery();

         AirlineFlights afs = new AirlineFlights();
         rpt.setAirlineFlights(afs);
         
         while (rs.next()) {
            AirlineFlights.AirlineFlight item = new AirlineFlights.AirlineFlight();
            item.setFlightNumber(rs.getString("flight_number"));
            item.setOrigin(rs.getString("origin"));
            item.setDestination(rs.getString("destination"));
            try {
               item.setArriveTime(dateFormat.parse(rs.getString("arrive_time")));
            } catch (ParseException e) {
               e.printStackTrace();
            }
            try {
               item.setDepartTime(dateFormat.parse(rs.getString("depart_time")));
            } catch (ParseException e) {
               e.printStackTrace();
            }
            item.setMiles(rs.getInt("miles"));
            item.setNumberOfSegments(rs.getInt("number_of_segments"));
            item.setAircraftType(rs.getString("aircraft_type"));
            afs.getAirlineFlight().add(item);
         }

         pstmt.close();

      } catch (SQLException e) {
         throw new SQLException("Exception in ReportSQL: " + e.getMessage());
      }

      JAXBElement<FlightListByAirlineReport> jaxbElement = new JAXBElement<FlightListByAirlineReport>(
            new QName("http://flightreports.googlecode.com/flightlist",
                  "FlightListByAirlineReport"),
            FlightListByAirlineReport.class, rpt);

      return jaxbElement;
   }
}
